package com.shexianyu.simple;

import java.util.HashMap;
import java.util.Map;

public class MatrixReshape {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        if (mat.length * mat[0].length != r * c) {
            return mat;
        }
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                map.put(count, mat[i][j]);
                count++;
            }
        }

        int[][] newMat = new int[r][c];
        int cnt = 0;
        for (int i = 0; i < newMat.length; i++) {
            for (int j = 0; j < newMat[i].length; j++) {
                if (count > cnt) {
                    newMat[i][j] = map.get(cnt);
                    cnt++;
                }
            }
        }
        return newMat;
    }

}
